package springmvc.web.cocktails;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import lombok.Data;

import org.dhbw.cocktail.Cocktail;
import org.dhbw.cocktail.Ingredient;
import org.dhbw.cocktail.mixer.ICocktailMixer;
import org.dhbw.cocktail.mixer.MixerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * Controller for AJAX-Based adding of an ingredient to the cocktail that is in creation
 * @author Roland von Werden
 *
 */
@Data
public class AddIngredientToEditCocktailController implements Controller {

	/**
	 * autowirde mixerfactory to access methods to create, get and search
	 * persisted Objects
	 */
	@Autowired
	@Qualifier("cocktail_mixer_factory")
	MixerFactory mixerFactory;
	ICocktailMixer mixer;

	@Override
	public ModelAndView handleRequest(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		ModelAndView mav = new ModelAndView();
		mixer = mixerFactory.getCocktailMixer();
		// Retrieve cocktail from session-object
		HttpSession session = arg0.getSession();
		Cocktail cocktail = null;
		if(session.getAttribute("new_cocktail") != null && session.getAttribute("new_cocktail") instanceof Cocktail) {
			cocktail = (Cocktail) session.getAttribute("new_cocktail");
		}
		else {
			cocktail = new Cocktail();
			session.setAttribute("new_cocktail", cocktail);
		}
		try {
			// Id and needed amount of the ingredient that is to be added
			long id = Long.valueOf(arg0.getParameter("id"));
			double amount = Double.valueOf(arg0.getParameter("amount"));
			// Retrieve ingredient from Persistence
			Ingredient ingr = mixer.getIngredientById(id);
			// Add ingredient to cocktail
			cocktail.addIngredient(ingr, amount);
			mav.addObject("id", id);
			mav.addObject("name", ingr.getName() + " Menge: " + amount + " " + ingr.getUnit());
		} catch (NumberFormatException e) {
			// TODO: handle exception
		}
		return mav;
	}

}
